package com.controller.back;

import com.entity.Book;
import com.entity.Category;
import com.github.pagehelper.PageInfo;
import com.service.BookService;
import com.service.CategoryService;
import com.util.ValidatorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("back/book")
public class BookController {
    @Autowired
    private BookService bookService;
    @Autowired
    private CategoryService categoryService;
    @RequestMapping("add")
    public String addBook(@ModelAttribute("b") @Validated Book book, MultipartFile pic,HttpServletRequest req, Model model) throws IOException {
        String realPath = req.getServletContext().getRealPath("/images/book/");
        FileCopyUtils.copy(pic.getInputStream(), new FileOutputStream(realPath + pic.getOriginalFilename()));

        System.out.println("b = " + book + ", pic = " + pic + ", req = " + req);
        book.setCover(pic.getOriginalFilename());
        book.setCreate_date(new Date());
        book.setSale(0);

        System.out.println("b = " + book);
        bookService.insertBook(book);
        return "redirect:/back/book/show.do";
    }
   //添加
    /*@RequestMapping("add")
    public String add(@ModelAttribute("b") Book book, MultipartFile pic, HttpServletRequest req) throws Exception {
        //获取输入流
        InputStream in = pic.getInputStream();
        System.out.println("in = " + in);
        //上传位置（Request 获取路径）
        String realPath = req.getServletContext().getRealPath("/images/book/");
        //获取文件名
        String filename = pic.getOriginalFilename();
        System.out.println("book = " + book + ", pic = " + pic);
        //获取输出流
        FileOutputStream out = new FileOutputStream(realPath+filename);
        //封装了上传下载流程（需要输入输出对象信息）
        FileCopyUtils.copy(in,out);
        //add.jsp收到的参数不够会导致失败
        //封面文件名
        book.setCover(filename);
        //添加时间
        book.setCreate_date(new Date());
        //销量
        book.setSale(0);
        //添加
        bookService.insertBook(book);

        return "redirect:/back/book/show.do";
    }*/
    @RequestMapping("batchRemove")
    public String batchRemoveBook(@RequestParam("ids") List<Integer> ids){
        for(Integer id:ids){
            bookService.deleteBookById(id);
        }
        return "redirect:/back/book/show.do";
    }
    @RequestMapping("remove")
    public String removeBook(Integer book_id, HttpSession session){
        try{
            bookService.deleteBookById(book_id);
        }catch(Exception e){
            e.printStackTrace();
            session.setAttribute("msg",e.getMessage() );
        }
        return "redirect:/back/book/show.do";

    }
    @RequestMapping("show")
    public String showAllBook(@RequestParam(defaultValue = "1")Integer pageNum,
                       @RequestParam(defaultValue = "3")Integer pageSize,
                       @RequestParam(defaultValue = "")String query,
                       @RequestParam(defaultValue = "")String value,
                       Model model){
        PageInfo<Book> books = bookService.selectPageBook(pageNum, pageSize,query,value);
        model.addAttribute("pageInfo", books);
        model.addAttribute("query",query);
        model.addAttribute("value",value);
        return "forward:/back/book/show.jsp";
    }
    @RequestMapping("showOne")
    public String showOneBook(Integer book_id,Model model){
        Book book = bookService.selectBookById(book_id);
        List<Category> categories = categoryService.selectCategoriesByLevels(2);
        model.addAttribute("book",book);
        model.addAttribute("categories",categories);
        return "forward:/back/book/update.jsp";
    }
    @RequestMapping("update")
    public String updateBook(@Validated Book book,MultipartFile pic ,BindingResult bindingResult, Model model,HttpServletRequest req) throws IOException {
        if(ValidatorUtils.handleBindingResult(bindingResult,model)){
            return "forward:/back/book/update.jsp";
        }
        if (pic != null && pic.getOriginalFilename() != null && !pic.getOriginalFilename().isEmpty()) {
            String realPath = req.getServletContext().getRealPath("/images/book/");
            FileCopyUtils.copy(pic.getInputStream(), new FileOutputStream(realPath + pic.getOriginalFilename()));
            book.setCover(pic.getOriginalFilename());
        }
        bookService.updateBook(book);
        return "redirect:/back/book/show.do";
    }
}
